package view;
import domain.Bill;
import domain.Cart;
import domain.Client;
import domain.Product;
import service.*;
import utils.SendMail;
import utils.Utility;
import utils.Validator;

import javax.mail.MessagingException;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;

public class TestSystem {
    AdminService adminService = new AdminService();
    ClientsService clientsService = new ClientsService();
    ProductService productService = new ProductService();
    CartService cartService = new CartService();
    BillService billService = new BillService();
    //在main函数里面创建一个new mainMenu();
    public static void main(String[] args) throws IOException, ClassNotFoundException,
            SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException,
            MessagingException, InterruptedException {
        new TestSystem().mainMenu();
    }
    
    //写主菜单，包括调用了userInterface()，adminInterface()
    public void mainMenu() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException, MessagingException, InterruptedException {
        while (true) {
            System.out.println("-----------------欢迎进入购物管理系统-----------------");
            System.out.println("                我是用户      选择：1                ");
            System.out.println("                我是管理员     选择:2                ");
            System.out.println("                退出         选择：0                ");
            System.out.println("请输入选择：");
            int in = Utility.readUnsignedInt();
            switch (in) {
                case 1:
                    userInterface();
                    break;
                case 2:
                    adminInterface();
                    break;
                case 0:
                    System.out.println("退出购物管理系统。");
                    return;
                default:
                    System.out.println("无效输入，请重新选择（1：用户，2：管理员，0：退出）");
            }

        }
    }
    
    //写用户登录界面，用户界面，以及购物界面菜单
    private void userInterface() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException, MessagingException, InterruptedException {
        while (true) {
            System.out.println("----------------欢迎进入用户登录界面-----------------");
            System.out.println("                登录       选择：1                ");
            System.out.println("                注册       选择：2                ");
            System.out.println("                忘记密码    选择：3                ");
            System.out.println("                退出       选择：0                ");
            System.out.println("请输入选择：");
            int in = Utility.readUnsignedInt();
            switch (in) {
                case 1:
                    Client clientR= userRegister();//实现用户的登录
                    if (clientR!= null) {
                        boolean loop = true;
                        while (loop) {
                            System.out.println("------------------欢迎进入用户界面--------------");
                            System.out.println("                购   物     选择：1                ");
                            System.out.println("                查看购物历史  选择：2                ");
                            System.out.println("                修改自身密码  选择：3                ");
                            System.out.println("                退   出     选择：0                ");
                            System.out.println("请输入你的选择：");
                            int input = Utility.readUnsignedInt(); // 读取用户输入,只能接受正整数
                            switch (input) {
                                case 1:
                                    boolean buyLoop = true;
                                    while (buyLoop) {
                                        System.out.println("==================  购物车操作 =================");
                                        System.out.println("         将商品加入购物车       选择：1");
                                        System.out.println("         将商品从购物车中移除    选择：2");
                                        System.out.println("         修改购物车中的商品数量   选择：3");
                                        System.out.println("         结  账               选择：4 ");
                                        System.out.println("         返回用户菜单           选择：0");
                                        System.out.println("请输入你的选择：");
                                        int choice = Utility.readUnsignedInt();
                                        switch (choice) {
                                            case 0:
                                                buyLoop = false;
                                                break;
                                            case 1:
                                                add2Cart(clientR.getClientID());
                                                break;
                                            case 2:
                                                removeFromCart(clientR.getClientID());
                                                break;
                                            case 3:
                                                updateQuantity(clientR.getClientID());
                                                break;
                                            case 4:
                                                pay(clientR.getClientID());
                                                break;
                                            default:
                                                System.out.println("输入选项错误！");
                                                break;
                                        }

                                    }
                                    break;
                                case 2:
                                    CheckBuyHistory(clientR.getClientID());
                                    break;
                                case 3:
                                    updatePassword(clientR.getClientID());
                                    break;
                                case 0:
                                    System.out.println("退出用户界面。");
                                    loop = false;
                                    break;
                                default:
                                    System.out.println("无效输入，请重新选择（1：购物，2：查看购物历史，3：修改自身密码，0：退出）");
                            }
                        }
                    } else {
                        System.out.println("密码错误次数过多，已被锁定30秒，稍后再试！");
                        Thread.sleep(30 * 1000);
                    }
                    break;
                case 2:
                    Login();
                    break;
                case 3:
                    resetAllowedByUser();
                    break;
                case 0:
                    System.out.println("退出登录界面。");
                    return;
                default:
                    System.out.println("无效输入，请重新选择（1：登录，2：注册，0：退出）");
            }
        }
    }
    
    //写管理员界面与实现功能
    private void adminInterface() throws SQLException, IOException, ClassNotFoundException, NoSuchFieldException,
            InstantiationException, IllegalAccessException, MessagingException {
        boolean Loginloop = true;
        while (Loginloop) {
            System.out.println("---------------欢迎进入管理员登录界面--------------");
            System.out.println("                   登录 选择：1                ");
            System.out.println("                   退出 选择：0                ");
            System.out.println("请输入选项: ");
            int choice = Utility.readUnsignedInt();
            switch (choice) {
                case 1:
                    System.out.println("请输入管理员名称：");
                    String name = Utility.readLine();
                    System.out.println("请输入密码：");
                    String pwd = Utility.readLine();
                    if (adminService.Login(name, pwd)) {
                        System.out.println("登录成功！");
                        boolean Userloop = true;
                        while (Userloop) {
                            System.out.println("-----------------欢迎进入管理员界面--------------");
                            System.out.println("                修改自身密码      选择：0                ");
                            System.out.println("                重置用户密码      选择：1                ");
                            System.out.println("                列出客户         选择：2                ");
                            System.out.println("                删除客户         选择：3                ");
                            System.out.println("                查询客户         选择：4                ");
                            System.out.println("                列出商品         选择：5                ");
                            System.out.println("                添加商品         选择：6                ");
                            System.out.println("                修改商品         选择：7                ");
                            System.out.println("                删除商品         选择：8                ");
                            System.out.println("                查询商品         选择：9                ");
                            System.out.println("                退   出         选择：-1                ");
                            System.out.println("请输入你的选择：");
                            int input = Utility.readInt(); // 读取用户输入
                            switch (input) {
                                case 0:
                                    updateA();
                                    break;
                                case 1:
                                    resetPassword();
                                    break;
                                case 2:
                                    listAllClients();
                                    break;
                                case 3:
                                    deleteOneClient();
                                    break;
                                case 4:
                                    boolean LoopQ = true;
                                    while (LoopQ) {
                                        System.out.println("---------------------查询客户信息----------------------");
                                        System.out.println("                 根据id    :    选择1");
                                        System.out.println("                 根据用户名 :    选择2");
                                        System.out.println("                 查询所有   :   选择0");
                                        System.out.println("                 退出      :   选择-1");
                                        System.out.println("输入你的选择：");
                                        int inputM = Utility.readInt();
                                        switch (inputM) {
                                            case 1:
                                                queryClientsById();
                                                break;
                                            case 2:
                                                queryClientsByName();
                                                break;
                                            case 0:
                                                listAllClients();
                                                break;
                                            case -1:
                                                LoopQ = false;
                                                break;
                                            default:
                                                System.out.println("选择输入错误！重新输入！");
                                                break;
                                        }
                                    }
                                    break;
                                case 5:
                                    listAllProducts();
                                    break;
                                case 6:
                                    addOrUpdateProduct(1);
                                    break;
                                case 7:
                                    listAllProducts();
                                    System.out.println("所有商品展示完毕，请依次输入修改后的信息!");
                                    addOrUpdateProduct(2);
                                    break;
                                case 8:
                                    deleteProduct();
                                    break;
                                case 9:
                                    queryProduct();
                                    break;
                                case -1:
                                    Userloop = false;
                                    System.out.println("已退出管理员界面");
                                    break;
                            }
                        }
                    } else {
                        System.out.println("登录失败");
                    }
                    break;
                // 其他选项逻辑...
                case 0:
                    Loginloop = false;
                    System.out.println("退出系统。");
                    break;
                default:
                    System.out.println("无效的输入，请重新输入！");

            }
        }
    }
    
    //修改管理员密码
    public void updateA() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        System.out.println("请输入管理员名称：");
        String name = Utility.readLine();
        System.out.println("请输入新的密码：");
        String pwd = Utility.readLine();
        if (adminService.updateAdmin(name, pwd)) {
            System.out.println("修改成功！");
            return;
        } else {
            System.out.println("修改失败！");
            return;
        }

    }

    //列出所有客户信息
    public void listAllClients() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        List<Client> list = clientsService.listAllClients();
        System.out.println("\t客户ID\t \t\t\t 用户名 \t\t\t 用户级别 \t\t用户注册时间\t \t\t\t累计消费金额 " +
                "\t\t\t累计消费金额" + "\t\t \t用户邮箱");
        for (Client c : list) {
            System.out.println(c);
        }
    }

    //删除客户信息
    public void deleteOneClient() throws SQLException, IOException, ClassNotFoundException {
        System.out.println("输入要删除的客户对应的id:");
        int id = Utility.readInt();
        System.out.println("是否执行删除操作？(y:执行   n:放弃):");
        char inputCh = Utility.readYOrN();
        if (inputCh == 'y') {
            boolean b = clientsService.deleteClient(id);
            if (b) {
                System.out.println("删除成功！");
            } else {
                System.out.println("id不存在，删除失败！");
            }
        } else {
            System.out.println("放弃删除！");
        }
    }

    //根据id查询用户
    public void queryClientsById() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        System.out.println("请输入要查询的客户对应的id:");
        int id = Utility.readInt();
        Client client = clientsService.queryClientsById(id);
        if (client != null) {
            System.out.println("\t客户ID\t \t\t\t 用户名 \t\t\t 用户级别 \t\t用户注册时间\t \t\t\t累计消费金额" +
                    " \t\t\t用户电话号码\t\t \t用户邮箱");
            System.out.println(client);
        } else {
            System.out.println("当前用户不存在！");
        }

    }

    //根据客户用户名查询信息
    public void queryClientsByName() throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println("请输入要查询的客户对应的用户名:");
        String username = Utility.readLine();
        Client client = clientsService.queryClientsByName(username);
        if (client != null) {
            System.out.println("\t客户ID\t \t\t\t 用户名 \t\t\t 用户级别 \t\t用户注册时间\t \t\t\t累计消费金额" +
                    " \t\t\t用户电话号码\t\t \t用户邮箱");
            System.out.println(client);
        } else {
            System.out.println("当前用户不存在！");
        }

    }

    //列出所有商品的信息
    public void listAllProducts() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        List<Product> list = productService.findAll();
        System.out.println(String.format("%-12s %-30s %-30s %-25s %-20s %-10s %-15s %-10s",
                "商品编号", "商品名称", "生产厂家", "生产日期", "型号", "进货价", "零售价格", "数量"));
        for (Product p : list) {
            System.out.println(p);
        }
    }

    //将添加商品addProduct()和修改商品updateProduct()的功能写到一个函数里面 ,提高代码的复用性
    public void addOrUpdateProduct(int i) throws SQLException, IOException, ClassNotFoundException,
            NoSuchFieldException, InstantiationException, IllegalAccessException {
        boolean Loop = true;
        while (Loop) {
            int productID;
            String productName;
            String manufacturer;
            Date productionDate;
            System.out.println("请输入商品名称:");
            productName = Utility.readLine();//商品名称、生产厂家、生产日期、型号、进货价、零售价格、数量。
            System.out.println("请输入生产厂家:");
            manufacturer = Utility.readLine();
            System.out.println("请输入生产日期:");
            while (true) {
                try {
                    String time = Utility.readLine();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate localDate = LocalDate.parse(time, formatter);
                    productionDate =
                            Date.from(localDate.atStartOfDay(java.time.ZoneId.systemDefault()).toInstant());
                    break;
                } catch (DateTimeParseException e) {
                    System.out.println("格式错误，请输入有效的日期格式（yyyy-MM-dd）：");
                }
            }
            System.out.println("请输入型号：");
            String model = Utility.readLine();
            System.out.println("输入进货价:");
            double purchasePrice =Utility.readDouble();
            System.out.println("输入零售价格是：");
            double retailPrice = Utility.readDouble();
            System.out.println("输入商品数量：");
            int quantity = Utility.readUnsignedInt();
            switch (i) {
                case 1:
                    if (productService.addProduct(productName, manufacturer, productionDate, model,
                            purchasePrice, retailPrice, quantity)) {
                        System.out.println("添加商品信息成功！");
                        Loop = false;
                    } else {
                        System.out.println("添加商品信息失败");
                    }
                    break;
                case 2:
                    System.out.println(""+"请输入修改的商品id："+"");
                    productID = Utility.readInt();
                    if (productService.updateProduct(productName, manufacturer, productionDate, model,
                            purchasePrice, retailPrice, quantity, productID)) {
                        System.out.println("修改成功！");
                        Loop = false;
                    } else {
                        System.out.println("需要要修改的商品ID不存在，修改失败！");
                    }
                    break;
            }
        }
    }

    //删除商品的信息
    public void deleteProduct() throws SQLException, IOException, ClassNotFoundException, NoSuchFieldException,
            InstantiationException, IllegalAccessException {
        listAllProducts();
        System.out.println("请输入要删除商品的ID(整数)：");
        int id = Utility.readInt();
        System.out.println("删除后无法恢复，请用户确认是否继续删除操作(y:确定   n:放弃)");
        char flag = Utility.readYOrN();
        if (flag == 'y') {
            if (productService.deleteProduct(id)) {
                System.out.println("删除成功！");
            } else {
                System.out.println("当前ID不存在，删除失败！");
            }
        } else {
            System.out.println("取消删除！");
        }
    }

    //查询商品的信息
    public void queryProduct() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        while (true) {
            String productName = "", manufacturer = "";
            double retailPrice = 0.0;
            System.out.println("---------------------查询选项---------------------");
            System.out.println("        根据商品名称单独查询：             1");
            System.out.println("        根据生产厂家单独查询：             2");
            System.out.println("        根据零售价格单独查询——指定价格：     3");
            System.out.println("        根据零售价格单独查询——指定价格以上：  4");
            System.out.println("        根据零售价格单独查询——指定价格以下：  5");
            System.out.println("        根据三者联合查询——指定价格：        6");
            System.out.println("        根据三者联合查询——指定价格以上：     7 ");
            System.out.println("        根据三者联合查询——指定价格以下：     8");
            System.out.println("        退出查询：                       0");
            System.out.println("请输入你的选择：");
            int choice = Utility.readUnsignedInt();
            List<Product> list1 = null;
            switch (choice) {
                case 0:
                    System.out.println("退出查询!");
                    return;
                case 1://根据商品名称单独查询
                    System.out.println("输入商品名称：");
                    productName = Utility.readLine();
                    list1 = productService.findByProductMessage(productName, manufacturer, retailPrice, choice);
                    break;
                case 2://根据生产厂家单独查询
                    System.out.println("输入生产厂家：");
                    manufacturer = Utility.readLine();
                    list1 = productService.findByProductMessage(productName, manufacturer, retailPrice, choice);
                    break;
                case 3, 4, 5: //根据零售价单独查询    查询价格相等的
                    list1 = queryO(productName, manufacturer, retailPrice, choice);
                    break;
                case 6, 7, 8://联合查询
                    list1 = query1(productName, manufacturer, retailPrice, choice);
                    break;
                default:
                    System.out.println("输入选项有误！");
                    break;
            }
            if (!list1.isEmpty()) {//如果数据库查不到数据返回的会是空集合，而不是null,防止空指针异常
                System.out.println(String.format("%-12s %-30s %-30s %-25s %-20s %-10s %-15s %-10s",
                        "商品编号", "商品名称", "生产厂家", "生产日期", "型号", "进货价", "零售价格", "数量"));
                for (Product p : list1) {
                    System.out.println(p);
                }
            } else {
                System.out.println("没有找到指定商品！");
            }
        }
    }

    //一个输入方法，解决单独查询的输入问题，减少代码量
    public List<Product> queryO(String productName, String manufacturer, double retailPrice, int choice) throws
            SQLException, IOException, NoSuchFieldException, ClassNotFoundException, InstantiationException,
            IllegalAccessException {
        System.out.println("输入零售价(小数)：");
        retailPrice = Utility.readDouble();
        List<Product> list1 = productService.findByProductMessage(productName, manufacturer, retailPrice, choice);
        return list1;
    }

    //一个输入方法，解决联合查询的输入问题，减少代码量
    public List<Product> query1(String productName, String manufacturer, double retailPrice, int choice) throws
            SQLException, IOException, NoSuchFieldException, ClassNotFoundException, InstantiationException,
            IllegalAccessException  {
        System.out.println("输入商品名称：");
        productName = Utility.readLine();
        System.out.println("输入生产厂家：");
        manufacturer = Utility.readLine();
        System.out.println("输入零售价(小数)：");
        retailPrice = Utility.readDouble();
        List<Product> list1 = productService.findByProductMessage(productName, manufacturer, retailPrice, choice);
        return list1;
    }

    //用户注册方法1
    public void Login() throws SQLException, IOException, ClassNotFoundException {
        while (true) {
            System.out.println("继续注册，请选择y;退出，请选择n：");
            if(Utility.readYOrN() == 'n'){
                break;
            }
            String username = "", passwordC = "", phoneNumber = "", email = "";
            while (true) {
                System.out.println("请输入用户名(用户名长度不少于5个字符)：");
                username = Utility.readLine();
                if (Validator.isValidUsername(username)) {
                    break;
                } else {
                    System.out.println("用户名输入错误，重新输入！");
                }
            }
            while (true) {
                System.out.println("请输入密码(密码长度大于8个字符，必须是大小写字母、数字和标点符号的组合):");
                passwordC = Utility.readLine();
                if (Validator.isValidPassword(passwordC)) {
                    break;
                } else {
                    System.out.println("密码输入不符合规范，重新输入！");
                }
            }
            while (true) {
                System.out.println("请输入电话号码:");
                phoneNumber = Utility.readLine();
                if (Validator.isValidPhone(phoneNumber)) {
                    break;
                } else {
                    System.out.println("电话号码输入错误，重新输入！");
                }
            }
            while (true) {
                System.out.println("请输入邮箱：");
                email = Utility.readLine();
                if (Validator.isValidEmail(email)) {
                    break;
                } else {
                    System.out.println("邮箱输入错误，重新输入！");
                }
            }
            if (clientsService.addClient(username, passwordC, phoneNumber, email)) {
                System.out.println("注册成功！");
                return;
            } else {
                System.out.println("注册失败！是否继续？(y:  是)");
                char str = Utility.readYOrN();
                if (str == 'y') {
                } else {
                    return;
                }
            }
        }
    }

    //商品加入到购物车
    public void add2Cart(Integer clientIDR) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        listAllProducts();
        while (true) {
            System.out.println("欢迎进入购物页面！(键盘输入1可退出页面，按任意键继续) ");
            if (Utility.readLine().equals("1")) {
                return;
            }
            System.out.println("请输入想要加入购物车的商品编号（整数）：");
            int id =Utility.readUnsignedInt();
            System.out.println("请输入该商品加入购物车的数量（整数，不能为负数）：");
            int num = Utility.readUnsignedInt();
            if (cartService.addCart(id, num, clientIDR)) {
                System.out.println("添加购物车成功！");
            } else {
                System.out.println("商品编号错误，添加失败！");
            }
        }
    }


    //将商品从购物车中移除，首先要显示购物车的所有商品
    public void removeFromCart(Integer clientIDR) throws SQLException, IOException, ClassNotFoundException,
            NoSuchFieldException, InstantiationException, IllegalAccessException {
        boolean b = listAllProduct(clientIDR);//如果购物车为空就不能移除商品
        if (b) {
            System.out.println("请输入想要移除购物车的商品编号（整数）：");
            Integer productID = Utility.readUnsignedInt();
            if (cartService.removeCart(productID, clientIDR)) {
                System.out.println("移除成功！");
            } else {
                System.out.println("商品编号错误，移除失败！");
            }
        } else {
            System.out.println("购物车为空，移除失败！");
        }
    }
    
    //显示某个用户购物车的所有商品，如果集合为空，就返回指定信息
    public boolean listAllProduct(Integer clientIDR) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        List<Cart> list = cartService.getCartList(clientIDR);
        if (!list.isEmpty()) {
            System.out.println("\t\t商品编号\t\t商品名称\t\t\t零售价\t\t数量\t\t\t型号");
            for (Cart cart : list) {
                System.out.println(cart);
            }
            return true;
        } else {
            System.out.println("购物车为空~~~");
            return false;
        }
    }

    //修改购物车中的商品数量
    public void updateQuantity(Integer clientIDR) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        boolean b = listAllProduct(clientIDR);
        if (b) {
            System.out.println("请输入想要修改数量的商品编号（整数）：");
            Integer productID = Utility.readUnsignedInt();
            System.out.println("请输入想要修改的数量（整数）：");
            Integer myQuantity = Utility.readInt();
            if(cartService.updateQuantity(productID,myQuantity,clientIDR)){
                System.out.println("修改成功！");
            }else{
                System.out.println("修改失败！");
            }
        }
    }

    // 结账操作有选择支付方式，删除在购物车表的信息，生成账单表，对商品表数量进行修改，对客户表的累计消费金额增加
    public void pay(Integer clientIDR) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        boolean b = listAllProduct(clientIDR);//如果购物车为空就不能结账
        if (b) {
            System.out.println("请输入要支付的商品编号:");
            int productID = Utility.readUnsignedInt();
            System.out.println("请输入支付方式(输入1，2，3分别表示支付宝、微信、银行卡):");
            String paymentMode=Utility.readPaymentMode();
            billService.addBill(productID,clientIDR,paymentMode);
        }else{
            System.out.println("当前购物车为空，不能结账~");
        }
    }

    //查看购买历史
    public void CheckBuyHistory(Integer clientIDR) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        List<Bill> list=billService.getAllBill(clientIDR);
        if (!list.isEmpty()) {
            System.out.println("\t\t商品编号\t\t\t商品名称\t\t加入购物车数量\t\t\t总金额\t\t\t\t支付时间" +
                    "\t\t\t\t\t\t支付方式");
            for (Bill bill : list) {
                System.out.println(bill);
            }
        }else{
            System.out.println("购物历史为空~");
        }
    }

    // 重置指定客户/用户的密码
    public void resetPassword() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException, MessagingException {
        listAllClients();
        System.out.println("请输入要重置密码的客户的ID：");
        while (true) {
            int ClientID=Utility.readUnsignedInt();
            String email=clientsService.getEmail(ClientID);
            if(email==null){
                System.out.println("输入的客户Id不存在！再试一次！");
            }else{
                String password = clientsService.updatePassword(ClientID);//得到新密码
                SendMail.sendMail(email,password);//调用工具方法，发送邮件到这个重置密码的用户
                break;
            }
        }

    }

    //用户修改自身密码修改自身密码
    public void updatePassword(Integer clientIDR) throws SQLException, IOException, ClassNotFoundException{
        System.out.println("请输入修改后的密码(密码长度大于8个字符，必须是大小写字母、数字和标点符号的组合):");
        while (true) {
            String newPassword=Utility.readLine();
            if(Validator.isValidPassword(newPassword)){
                clientsService.updateMyPassword(newPassword,clientIDR);
                System.out.println("密码修改成功!");
                break;
            }else{
                System.out.println("密码输入不符合要求，重新输入！");
            }
        }

    }

    //忘记密码：可以让自行重置密码（需要对输入的用户名判断存在与否，再判断这个用户名是不是对应这个邮箱，否则重新输入）
    public void resetAllowedByUser() throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException, MessagingException {
        System.out.println("请输入您的用户名：");
        while (true) {
            String username = Utility.readLine();
            Client client=clientsService.judgeExist(username);
            if(client==null){
                System.out.println("当前用户名不存在，再试一次！");
            }else{
                System.out.println("请输入您注册该账号所使用的邮箱地址：");
                while (true) {
                    String email=Utility.readLine();
                    if(email.equals(client.getEmail())){
                        String password = clientsService.updatePassword(client.getClientID());
                        //更新用户密码并得到新密码
                        SendMail.sendMail(email,password);//调用工具方法，发送邮件到这个重置密码的用户
                        break;
                    }else{
                        System.out.println("邮箱地址不正确，再试一次！");
                    }
                }
                break;
            }
        }





    }

    //用户登录：密码连续输入错误5次就锁定账户。
    //登录，用户输入账户名查询账户是否存在，是就再输入密码（密码错误就记录错误次数，给出提示，在五次内登录上次数清0，否则锁户
    // 在数据库里面查询是否存在这样一个用户
    public Client userRegister() throws SQLException, IOException, NoSuchFieldException, ClassNotFoundException,
            InstantiationException, IllegalAccessException, MessagingException, InterruptedException {
        System.out.println("请输入用户名：");
        while (true) {
            String username = Utility.readLine();
            Client client1 = clientsService.judgeExist(username);
            if(client1==null){
                System.out.println("当前用户不存在！再试一次！");
            }else{
                System.out.println("请输入密码：");
                while (true) {
                    String password=Utility.readLine();
                    if(clientsService.judge(client1.getClientID(),password)){
                        System.out.println("登录成功!");
                        clientsService.updateState0(client1.getClientID());//在五次内登录上次数清0
                        return client1;
                    }else{
                        int num = clientsService.updateState(client1.getClientID());//更新次数
                        if(num==5){
                            clientsService.updateState0(client1.getClientID());
                            return null;
                        }
                        System.out.println("密码错误，仅剩"+(5-num)+"次机会！");
                    }
                }
            }
        }

    }

}